package com.ayz.gateway.center.infrastructure.notify;

import com.ayz.gateway.center.infrastructure.exception.GatewayServiceDeployerException;
import com.ayz.gateway.center.infrastructure.nginx.GatewayServiceDeployer;
import com.ayz.gateway.center.infrastructure.nginx.NgxConfigMetadata;
import com.ayz.gateway.center.infrastructure.nginx.docker.DockerGatewayServiceDeployer;
import com.ayz.gateway.common.notify.ApplicationListener;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @ClassName GatewayServiceChangeEventListener
 * @Description TODO: 网关服务变更事件监听器
 * 网关服务注册 注销 不健康剔除情况发生都会被当前监听器监听到
 * @Author 快乐的星球
 * @Date 2023/6/12 11:54
 * @Version 1.0
 **/
@Getter
@Setter
public class GatewayServiceChangeEventListener implements ApplicationListener<GatewayServiceChangeEvent> {

    private static final Logger LOG= LoggerFactory.getLogger(GatewayServiceChangeEventListener.class);
    public static String NGX_CONFIG_PATH_IN_CENTER="/etc/nginx/conf/nginx.conf";

    public static String NGX_CONFIG_IN_NGINX="/etc/nginx/nginx.conf";
    /**
     * 网关服务的部署器
     */
    private GatewayServiceDeployer gatewayServiceDeployer;

    public GatewayServiceChangeEventListener(String ngxContainerName) {
        NgxConfigMetadata metadata=new NgxConfigMetadata();
        metadata.setNgxContainerName(ngxContainerName);
        metadata.setNgxConfigPathInCenter(NGX_CONFIG_PATH_IN_CENTER);
        metadata.setNgxConfigPathInNgx(NGX_CONFIG_IN_NGINX);

        gatewayServiceDeployer=new DockerGatewayServiceDeployer(metadata);
        try {
            LOG.info("网关服务部署器开始初始化..........");
            gatewayServiceDeployer.init();
        } catch (IOException e) {
            throw new RuntimeException("NgxConfig创建失败 或者 DockerClient创建失败!");
        }
    }

    @Override
    public void onApplicationEvent(GatewayServiceChangeEvent event) {
       GatewayServiceChangeEvent.GatewayServiceMetadata gatewayServiceMetadata
               =(GatewayServiceChangeEvent.GatewayServiceMetadata) event.getSource();
       //GatewayServiceDeployer进行部署
        try {
            getGatewayServiceDeployer().deploy(gatewayServiceMetadata);
        } catch (Exception e) {
            throw new GatewayServiceDeployerException("部署网关服务异常!GatewayServiceChangeEvent:{"+event+"}");
        }
    }
}
